package com.android.cattlefarm;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.cattlefarm.db.AddDB;
import com.android.cattlefarm.db.ImportDB;
import com.android.cattlefarm.util.Constants;
import com.android.cattlefarm.util.ExportEntity;
import com.android.cattlefarm.util.FileEntity;
import com.android.cattlefarm.util.FileUtil;
import com.android.cattlefarm.util.ImportEntity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;


/**
 * Created by Huang on 2015/7/4.
 */
public class ExportActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
    public static String columnName[] = {"注册牛号",
            "牛场号",
            "牛场名",
            "出生日期",
            "胎次",
            "产犊日期",
            "父亲",
            "母亲",
            "外祖父",
            "体高",
            "胸宽",
            "体深",
            "腰强度",
            "尻角度",
            "尻宽",
            "蹄角度",
            "蹄踵深度",
            "骨质地",
            "后肢侧视",
            "后肢后视",
            "乳房深度",
            "中央悬韧带",
            "前乳房附着",
            "前乳头位置",
            "前乳头长度",
            "后附着高度",
            "后附着宽度",
            "后乳头位置",
            "棱角性",
            "体躯容量",
            "尻部",
            "肢蹄",
            "泌乳系统",
            "前乳房",
            "后乳房",
            "乳用特征",
            "加权总分",};
    private ListView mListView;
    private List<FileEntity> filesList = new ArrayList<>();
    private FileAdapter fileAdapter;
    private String fileParentPath;
    private String currentPath;
    private Button saveBtn, createBtn;
    private String selectFilePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_import);
        mListView = (ListView) findViewById(R.id.import_list);
        saveBtn = (Button) findViewById(R.id.title_right);
        createBtn = (Button) findViewById(R.id.title_create);
        mListView.setOnItemClickListener(this);
        saveBtn.setOnClickListener(this);
        createBtn.setOnClickListener(this);
        createBtn.setVisibility(View.VISIBLE);
        saveBtn.setVisibility(View.VISIBLE);
        saveBtn.setText("导出文件");
        setCurrentFile(ImportActivity.ROOT_FILE_PATH);
    }

    private void setCurrentFile(String path) {
        if (path == null || path.equals("")) return;
        filesList.clear();
        File file = new File(path);
        currentPath = path;
        fileParentPath = file.getParentFile().getAbsolutePath();
        if (file.isDirectory()) {
            File flist[] = file.listFiles();
            for (int i = 0; i < flist.length; i++) {
                File currentFile = flist[i];
                FileEntity fileEntity = new FileEntity();
                fileEntity.setPath(currentFile.getAbsolutePath());
                fileEntity.setName(currentFile.getName());
                fileEntity.setModifyTime(currentFile.lastModified());
                if (currentFile.isDirectory()) {
                    fileEntity.setIsDirectory(true);
                    try {
                        fileEntity.setFileCount(currentFile.listFiles().length);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                filesList.add(fileEntity);
            }
        }
        fileAdapter = new FileAdapter(this, filesList);
        mListView.setAdapter(fileAdapter);
    }

    @Override
    public void onClick(View v) {
        if (v == createBtn) {
            final EditText inputServer = new EditText(this);
            inputServer.setMaxHeight(120);
            AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom));
            builder.setTitle("输入文件名称").setView(inputServer)
                    .setNegativeButton("取消", null);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    if (inputServer.getText().toString().trim().equals("")) return;
                    File file = new File(currentPath + File.separator + inputServer.getText().toString());
                    if (!file.exists()) {
                        boolean create = file.mkdirs();
                        if (create) {
                            inputServer.setText("");
                            showMessage("文件夹创建成功");
                            setCurrentFile(currentPath);
                        }
                    }
                }
            });
            builder.show();
        } else {
            if (currentPath != null) {
                final EditText inputServer = new EditText(this);
                inputServer.setMaxHeight(120);
                inputServer.setText(getFileName());
                AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom));
                builder.setTitle("输入文件名称").setView(inputServer)
                        .setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        if (inputServer.getText().toString().trim().equals("")) return;
                        saveFile(inputServer.getText().toString());
                    }
                });
                builder.show();
            }

            ;
        }
    }

    private String getFileName() {
        AddDB importDB = new AddDB(this);

        List<ExportEntity> dataList = importDB.queryExportList();
        importDB.closeDataBase();
        if (dataList == null || dataList.size() == 0) return "";
        ExportEntity entity = dataList.get(0);
        StringBuffer sb = new StringBuffer();
        sb.append(entity.getCowfarmName());
        sb.append("_");
        sb.append(entity.getCowfarmNum());
        return sb.toString();
    }

    private void saveFile(String fileName) {
        showLoading();
        if (createTempXls(currentPath + File.separator + fileName + ".xls")) {
            showMessage("保存成功");
            setCurrentFile(currentPath);
        }
        hideLoading();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        FileEntity fileEntity = (FileEntity) mListView.getAdapter().getItem(position);
        if (fileEntity == null) return;

        if (fileEntity.isDirectory())
            setCurrentFile(fileEntity.getPath());
        else {
            if (fileEntity.getName().endsWith("xls")) {
                selectFilePath = fileEntity.getPath();
                AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom));
                builder.setTitle("打开这个文件?");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        FileUtil.openFile(ExportActivity.this, selectFilePath);
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.create().show();

            }
        }
    }

    public void backClick(View v) {
        if (fileParentPath != null && !fileParentPath.equals(ImportActivity.ROOT_FILE_PARENT_PATH)) {
            setCurrentFile(fileParentPath);
        } else {
            finish();
        }
    }

    public boolean createTempXls(String fileName) {
        boolean success = true;
        WritableWorkbook wwb = null;
        try {
            //创建一个可写入的工作薄(Workbook)对象
            wwb = Workbook.createWorkbook(new File(fileName));
        } catch (IOException e) {
            success = false;
            e.printStackTrace();
        }
        if (wwb != null) {
            // 第一个参数是工作表的名称，第二个是工作表在工作薄中的位置
            WritableSheet ws = wwb.createSheet("sheet1", 0);
            for (int i = 0; i < columnName.length; i++) {
                Label lbl = new Label(i, 0, columnName[i]);
                try {
                    ws.addCell(lbl);
                } catch (RowsExceededException e1) {
                    e1.printStackTrace();
                    success = false;
                } catch (WriteException e1) {
                    e1.printStackTrace();
                    success = false;
                }
            }
            AddDB addDB = new AddDB(this);
            List<ExportEntity> allDataList = addDB.queryExportList();
            if (allDataList == null) success = false;
            else {
                List<ExportEntity> dataList = new ArrayList<>();
//                List<ExportEntity> emptydataList = new ArrayList<>();
//                List<ExportEntity> hadDataList = new ArrayList<>();
//                for (ExportEntity entity : allDataList) {
//                    if (entity.getAverage() > 0.0f) {
//                        hadDataList.add(entity);
//                    } else {
//                        emptydataList.add(entity);
//                    }
//                }
//                dataList.addAll(hadDataList);
                dataList.addAll(allDataList);
                for (int i = 0; i < dataList.size(); i++) {
                    int modifyPos = i + 1;
                    ExportEntity exportEntity = dataList.get(i);
                    Label lbl1 = new Label(0, modifyPos, exportEntity.getCowNum());
                    Label lbl2 = new Label(1, modifyPos, exportEntity.getCowfarmNum());
                    Label lbl3 = new Label(2, modifyPos, exportEntity.getCowfarmName());
                    Label lbl4 = new Label(3, modifyPos, exportEntity.getBirthday());
                    Label lbl5 = new Label(4, modifyPos, exportEntity.getTyre());
                    Label lbl6 = new Label(5, modifyPos, exportEntity.getProductionTime());
                    Label lbl7 = new Label(6, modifyPos, exportEntity.getFather());
                    Label lbl8 = new Label(7, modifyPos, exportEntity.getMother());
                    Label lbl9 = new Label(8, modifyPos, exportEntity.getGrandfather());

                    try {
                        ws.addCell(lbl1);
                        ws.addCell(lbl2);
                        ws.addCell(lbl3);
                        ws.addCell(lbl4);
                        ws.addCell(lbl5);
                        ws.addCell(lbl6);
                        ws.addCell(lbl7);
                        ws.addCell(lbl8);
                        ws.addCell(lbl9);
                    } catch (RowsExceededException e1) {
                        e1.printStackTrace();
                        success = false;
                    } catch (WriteException e1) {
                        e1.printStackTrace();
                        success = false;
                    }
                    if (exportEntity.getColumnValue() != null && exportEntity.getColumnValue().length > 0)
                        for (int j = 0; j < exportEntity.getColumnValue().length; j++) {

                            Label lbl = new Label(j + 9, modifyPos, String.valueOf(exportEntity.getColumnValue()[j]));
                            try {
                                ws.addCell(lbl);
                            } catch (RowsExceededException e1) {
                                e1.printStackTrace();
                                success = false;
                            } catch (WriteException e1) {
                                e1.printStackTrace();
                                success = false;
                            }
                        }


                    try {
                        if (exportEntity.getTiqurongliang() > 0.0f) {
                            Label lbl10 = new Label(29, modifyPos, exportEntity.getTiqurongliang() + "");
                            ws.addCell(lbl10);
                        }
                        if (exportEntity.getKaobu() > 0.0f) {
                            Label lbl11 = new Label(30, modifyPos, exportEntity.getKaobu() + "");
                            ws.addCell(lbl11);
                        }
                        if (exportEntity.getZhiti() > 0.0f) {
                            Label lbl12 = new Label(31, modifyPos, exportEntity.getZhiti() + "");
                            ws.addCell(lbl12);
                        }
                        if (exportEntity.getXitong() > 0.0f) {
                            Label lbl13 = new Label(32, modifyPos, exportEntity.getXitong() + "");
                            ws.addCell(lbl13);
                        }
                        if (exportEntity.getQianrufang() > 0.0f) {
                            Label lbl14 = new Label(33, modifyPos, exportEntity.getQianrufang() + "");
                            ws.addCell(lbl14);
                        }
                        if (exportEntity.getHourufang() > 0.0f) {
                            Label lbl15 = new Label(34, modifyPos, exportEntity.getHourufang() + "");
                            ws.addCell(lbl15);
                        }
                        if (exportEntity.getRuyongtezheng() > 0.0f) {
                            Label lbl16 = new Label(35, modifyPos, exportEntity.getRuyongtezheng() + "");
                            ws.addCell(lbl16);
                        }
                    } catch (RowsExceededException e1) {
                        e1.printStackTrace();
                        success = false;
                    } catch (WriteException e1) {
                        e1.printStackTrace();
                        success = false;
                    }
                    if (exportEntity.getAverage() > 0.0f) {
                        Label lbl11 = new Label(36, modifyPos, String.valueOf(exportEntity.getAverage()));
                        try {
                            ws.addCell(lbl11);
                        } catch (RowsExceededException e1) {
                            success = false;
                            e1.printStackTrace();
                        } catch (WriteException e1) {
                            e1.printStackTrace();
                            success = false;
                        }
                    }
                }
            }
            try {
                wwb.write();
                wwb.close();
            } catch (IOException e) {
                success = false;
                e.printStackTrace();
            } catch (WriteException e) {
                success = false;
                e.printStackTrace();
            }
        }
        if(!success){
            showMessage("导出失败,请确认录入数据是否正确!");
        }
        return success;
    }

    private void showMessage(String str) {
        Toast toast = new Toast(this);
        View toastView = LayoutInflater.from(this).inflate(R.layout.toast_text, null);
        TextView textView = (TextView) toastView.findViewById(R.id.toast_text);
        textView.setText(str);
        toast.setView(toastView);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 10);
        toast.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (fileParentPath != null && !fileParentPath.equals(ImportActivity.ROOT_FILE_PARENT_PATH)) {
                setCurrentFile(fileParentPath);
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
